import {
  BadRequestException,
  Body,
  Controller,
  Get,
  ParseIntPipe,
  Post,
  Query,
  Res,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { Response } from 'express';

import { FileInterceptor } from '@nestjs/platform-express';
import { UploadService } from './upload.service';
import { existsSync } from 'fs';
import * as sharp from 'sharp';
@Controller()
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      dest: 'uploads',
    }),
  )
  uploadFile(@UploadedFile() file: Express.Multer.File) {
    // console.log('file', file);
    return file.path;
  }
  @Get('compressionGif')
  async compressionGif(
    @Query('path') filePath: string,
    @Query('color', ParseIntPipe) color: number,
    @Res() res: Response,
  ) {
    if (!existsSync(filePath)) {
      throw new BadRequestException('文件不存在');
    }

    try {
      const data = await sharp(filePath, {
        animated: true,
        limitInputPixels: false,
      })
        .gif({
          colours: color,
        })
        .toBuffer();

      res.set('Content-Disposition', `attachment; filename="dest.gif"`);

      res.send(data);
    } catch (error) {
      console.log(error);
    }
  }
  @Get('compressionImg')
  async compressionImg(
    @Query('path') filePath: string,
    @Query('quality', ParseIntPipe) quality: number,
    @Res() res: Response,
  ) {
    if (!existsSync(filePath)) {
      throw new BadRequestException('文件不存在');
    }

    try {
      const data = await sharp(filePath, {
        animated: true,
        limitInputPixels: false,
      })
        // .resize(800, 600) // 缩放图片
        .jpeg({ quality: 20 }) // 设置 JPEG 图片质量
        .toBuffer();
      res.set('Content-Disposition', `attachment; filename="dest.jpeg"`);

      res.send(data);
    } catch (error) {
      console.log(error);
    }
  }
}
